﻿using System;
using System.Text;
using System.Web.Mvc;
using System.Web.Routing;

namespace MShop.Web.Components.Paging
{
	public class Pager
	{
		private ViewContext viewContext;
		private readonly int pageSize;
		private readonly int currentPage;
		private readonly int totalItemCount;
		private readonly RouteValueDictionary linkWithoutPageValuesDictionary;

		public Pager(ViewContext viewContext, int pageSize, int currentPage, int totalItemCount, RouteValueDictionary valuesDictionary)
		{
			this.viewContext = viewContext;
			this.pageSize = pageSize;
			this.currentPage = currentPage;
			this.totalItemCount = totalItemCount;
			this.linkWithoutPageValuesDictionary = valuesDictionary; 
           
		}




        public string RenderHtml()
        {
           return RenderHtml(HttpVerbs.Get,string.Empty);
        }

        public string RenderHtml(HttpVerbs verbs, string domid, string formname)
        {
            int pageCount = (int)Math.Ceiling(this.totalItemCount / (double)this.pageSize);
            int nrOfPagesToDisplay = 10;

            var sb = new StringBuilder();
            sb.Append("<div class='pagination'>");
            sb.Append("<div class='pagination_1'>");

            string key = this.viewContext.HttpContext.Items[this.viewContext.Controller.ToString()] as string;
            if (key == null)
            {
                System.Text.StringBuilder sbscript = new StringBuilder();
                sbscript.Append("<script  type=\"text/javascript\" >");
                sbscript.Append("\nfunction mvcgopage(index){");
                sbscript.Append("document.getElementById(\"" + domid + "\").value = index;");
                //sbscript.Append("alert(document.getElementById(\"" + domid + "\").value);");
                //sbscript.Append("\n");
                if (string.IsNullOrEmpty(formname))
                {
                    sbscript.Append("var frm=document.forms[0];frm.submit();");
                }
                else
                {
                    sbscript.Append("var frm=document.forms['"+ formname+"'];frm.submit();");
                }
               // sbscript.Append("\n");
                sbscript.Append("}");
                sbscript.Append("</script>");
                this.viewContext.HttpContext.Items[this.viewContext.Controller.ToString()] = sbscript.ToString();
                sb.Append(sbscript.ToString());
            }


            // Previous
            if (this.currentPage > 1)
            {
                sb.Append(GeneratePageLink("上一页", this.currentPage - 1, verbs,"prev"));
            }
            else
            {
                sb.Append("<span class=\"disabled\">上一页</span>");
            }

            int start = 1;
            int end = pageCount;

            if (pageCount > nrOfPagesToDisplay)
            {
                int middle = (int)Math.Ceiling(nrOfPagesToDisplay / 2d) - 1;
                int below = (this.currentPage - middle);
                int above = (this.currentPage + middle);

                if (below < 4)
                {
                    above = nrOfPagesToDisplay;
                    below = 1;
                }
                else if (above > (pageCount - 4))
                {
                    above = pageCount;
                    below = (pageCount - nrOfPagesToDisplay);
                }

                start = below;
                end = above;
            }

            if (start > 3)
            {
                sb.Append(GeneratePageLink("1", 1));
                sb.Append(GeneratePageLink("2", 2));
                sb.Append("...");
            }
            for (int i = start; i <= end; i++)
            {
                if (i == this.currentPage)
                {
                    sb.AppendFormat("<span class=\"current\">{0}</span>", i);
                }
                else
                {
                    sb.Append(GeneratePageLink(i.ToString(), i, verbs,null));
                }
            }
            if (end < (pageCount - 3))
            {
                sb.Append("...");
                sb.Append(GeneratePageLink((pageCount - 1).ToString(), pageCount - 1, verbs,null));
                sb.Append(GeneratePageLink(pageCount.ToString(), pageCount, verbs,null));
            }

            // Next
            if (this.currentPage < pageCount)
            {
                sb.Append(GeneratePageLink("下一页", (this.currentPage + 1), verbs,"next"));
            }
            else
            {
                sb.Append("<span class=\"disabled\">下一页</span>");
            }
            sb.Append("</div>");
            sb.Append("</div>");

            if (totalItemCount < pageSize)
                return string.Empty;
            return sb.ToString();
        }

        public string RenderHtml(HttpVerbs verbs,string domid)
		{
            return RenderHtml(verbs, domid, string.Empty);			
		}

        private string GeneratePageLink(string linkText, int pageNumber, HttpVerbs verbs,string @class)
		{
            if (verbs == HttpVerbs.Get)
            {
                var pageLinkValueDictionary = new RouteValueDictionary(this.linkWithoutPageValuesDictionary);
                pageLinkValueDictionary.Add("page", pageNumber);
                //UrlHelper.GenerateUrl(null,viewContext.RouteData.Values["action"].ToString(),viewContext.RouteData.Values["controller"].ToString()
                //    ,pageLinkValueDictionary,this.h
                var virtualPathData = this.viewContext.RouteData.Route.GetVirtualPath(this.viewContext.RequestContext, pageLinkValueDictionary);
              //  var virtualPathData = RouteTable.Routes.GetVirtualPath(this.viewContext.RequestContext, pageLinkValueDictionary);
                if (virtualPathData != null)
                {
                    string tmpclass = @class != null ? "class="+ @class+"" : "";
                    string linkFormat = "<a "+ tmpclass+" href=\"/{0}\">{1}</a>";
                    return String.Format(linkFormat, virtualPathData.VirtualPath, linkText);
                }
                else
                {
                    return null;                    
                }
            }
            else//post
            {
                string linkFormat = "<a href='javascript:void(" + pageNumber + ");' onclick=\"mvcgopage({0});\">{1}</a>";
                return String.Format(linkFormat, pageNumber, linkText);               
            }
		}


        private string GeneratePageLink(string linkText, int pageNumber)
        {
            return GeneratePageLink(linkText, pageNumber, HttpVerbs.Get,null);
        }
	}
}